#include "rgb.h"
#include "temp.h"
#include "fan.h"
#include "pthread.h"
#include "oled.h"
#include "msgd.h"
#include "ssd1306_i2c.h"
#include "head.h"


pthread_t t_rgb,t_fan,t_oled,t_ile;
pthread_barrier_t thread_wait;

int fd_pid;
int slp_rgb = 10;
int slp_fan = 10;
int slp_oled = 2;


void my_exit()
{
    pthread_barrier_destroy(&thread_wait);
    pthread_cancel(t_rgb);
    pthread_cancel(t_fan);
    pthread_cancel(t_oled);
    pthread_cancel(t_ile);
    clear_screen();
    closeRGB();
    setFan(0);
    close(fd_pid);
    unlink(PID_FILE);
    clear_screen();
    exit(0);
}

void check_run()
{
    if(access(PID_FILE,F_OK) == 0)
    {
        perr_d(true,LOG_ERR,"service has already started");
        exit(-1);
    }
    else
    {
        fd_pid = open(PID_FILE,O_CREAT|O_RDWR|O_TRUNC,S_IRUSR|S_IWUSR);
        char buf[12] = {'\0'};
        sprintf(buf,"%d",getpid());
        write(fd_pid,buf,strlen(buf));
    }
}

void * ile(void * arg)
{
    while (1)
    {
        sleep(slp_rgb);
        pthread_barrier_wait(&thread_wait);
    }
}

void turn_off_light()
{
    pthread_cancel(t_ile);
    pthread_cancel(t_rgb);
    closeRGB();
    pthread_create(&t_ile,NULL,ile,NULL);
    signal(SIGUSR1,turn_off_light);
    return ;
}

void turn_on_light()
{
    pthread_cancel(t_ile);
    pthread_cancel(t_rgb);
    pthread_create(&t_rgb,NULL,tempRGB_thread,&slp_rgb);
    signal(SIGUSR2,turn_on_light);
    return ;
}


int main(int argc,char * argv[])
{

    daemon(0,0);
    atexit(my_exit);
    check_run();
    initFan();
    initRGB();
    initOled();


    signal(SIGINT,my_exit);
    signal(SIGTERM,my_exit);
    signal(SIGUSR1,turn_off_light);
    signal(SIGUSR2,turn_on_light);


    pthread_barrier_init(&thread_wait,NULL,2);

    pthread_create(&t_rgb,NULL,tempRGB_thread,&slp_rgb);
    pthread_create(&t_fan,NULL,tempFan_thread,&slp_fan);
    pthread_create(&t_oled,NULL,default_show_thread,&slp_oled);


    sleep(3);
    if(access("/pi/home/fan_light_off",F_OK) == 0)
        turn_off_light();


    pthread_join(t_rgb,NULL);
    pthread_join(t_fan,NULL);
    pthread_join (t_oled, NULL);


    return 0;
}